package com.woyou.ui.activity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import com.citaq.ideliver.R;
import com.woyou.Constant;
import com.woyou.bean.CodeResult;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.CheckUpdateReq;
import com.woyou.bean.rpc.CheckUpdateRes;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.component.CheckUpdateDialog;
import com.woyou.ui.component.EditDialog;
import com.woyou.utils.DeviceUtils;
import com.woyou.utils.Dialog;
import com.woyou.utils.FileUtils;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.eventbus.EventInfoSetup;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
import retrofit.RetrofitError;

/**
 * 设置SetUpFragment
 * 
 * @author tanglc
 */
@EActivity(R.layout.fm_setup)
public class MySetUpActivity extends BaseActivity implements IBackEventStrategy {

	Dialog dialog = new Dialog();
	EditDialog editDialog = new EditDialog();
	String UPDATE_SERVERAPK = "ideliver.apk";
	ProgressDialog pd = null;
	double lat;
	double lng;
	String downloadUrl;
	CheckUpdateDialog checkDialog = new CheckUpdateDialog();

	@ViewById // 非Wifi下图片质量、检查更新、更新提示框
	LinearLayout fm_set_picqualitybtn, fm_set_checkupdatebtn, updatedialog;
	@ViewById // 退出设置界面
	RelativeLayout myback;
	@ViewById // 标题头、检查更新、清除缓存图片、图片质量、更新内容、新版本号、新版本大小、发布时间
	TextView head_title, fm_set_checkupdatetext, fm_set_removepictext, fm_set_picqualitytext, updatelog, versionno,
			versionsize, updatetime;
	@ViewById
	Button cancle_button, ok_button;

	@AfterViews
	public void init() {
		initView();
	}

	@Override
	public void onResume() {
		super.onResume();
		init();
	}

	@Override
	public void onPause() {
		super.onPause();
		editDialog.dismiss();
		dialog.dismiss();
		updatedialog.setVisibility(View.GONE);
		checkDialog.dismiss();
	}

	@Click({ R.id.fm_set_removepicbtn, R.id.fm_set_picqualitybtn, R.id.fm_set_checkupdatebtn, R.id.myback,
			R.id.coveronclick, R.id.cancle_button, R.id.ok_button, R.id.updatedialog })
	void loginOnClick(View view) {
		switch (view.getId()) {
		case R.id.myback:
			// 退出设置界面
			// clazz = MySetUpFragment_.class;
			// BusProvider.getInstance().post(DestoryFM());
			finish();
			break;

		case R.id.fm_set_checkupdatebtn:
			// 检查更新
			checkUpdate();
			break;

		case R.id.fm_set_removepicbtn:
			// 清除图片缓存
			editDialog.Dialog(mActivity, fm_set_removepictext, R.id.fm_set_removepictext, "确认清除图片缓存吗？", "isDialog");
			break;

		case R.id.fm_set_picqualitybtn:
			// 非Wifi下图片质量
			editDialog.Dialog(mActivity, fm_set_picqualitytext, R.id.fm_set_picqualitytext, "非WiFi下图片质量", "isRadio");
			break;

		case R.id.updatedialog:
			// 非Wifi下图片质量
			updatedialog.setVisibility(View.GONE);
			break;

		// case R.id.cancle_button:
		// // 取消更新
		// updatedialog.setVisibility(View.GONE);
		// break;
		// case R.id.ok_button:
		// 立即更新
		// dialog.Toast(mActivity, "是否更新最新版本！");
		// pd = new ProgressDialog(mActivity);
		// pd.setTitle("正在下载");
		// pd.setMessage("请稍后...");
		// pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// downFile(downloadUrl);
		// break;
		default:
			break;
		}
	}

	public void initView() {
		head_title.setText("设置");
		String versionName = getAppVersionName(mActivity);
		fm_set_checkupdatetext.setText("当前版本V" + versionName);
		fm_set_removepictext.setText(FileUtils.getDiskCacheSize(mContext));
		updatelog.setMovementMethod(ScrollingMovementMethod.getInstance());
		if (LocationLoopService.getInstance(mContext).getChosenAddr() != null) {
			lat = Double.valueOf(LocationLoopService.getInstance(mContext).getChosenAddr().getLat());
			lng = Double.valueOf(LocationLoopService.getInstance(mContext).getChosenAddr().getLng());
		} else {
			if (mBaiduLocationService.getLastLocation() != null) {
				lat = mBaiduLocationService.getLastLocation().getLatitude();
				lng = mBaiduLocationService.getLastLocation().getLongitude();
			}
		}
	}

	/**
	 * 返回当前程序版本名
	 */
	public String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
		}
		return versionName;
	}

	@Background
	void checkUpdate() {
		if (!NetWorkCenter.isNetworkConnected(getBaseContext())) {
			showToast("请检查你的网络!");
			return;
		}
		showProgressDialog();
		try {
			UserInfo userInfo = mUserModel.getUserInfo();
			CheckUpdateReq checkUpdateReq = new CheckUpdateReq();
			checkUpdateReq.setuId(userInfo.getuId());
			checkUpdateReq.setPwd(userInfo.getPwd());
			checkUpdateReq.setCityName(userInfo.getCity().getCity());
			checkUpdateReq.setDeviceInfo(DeviceUtils.getDeviceInfo(mContext));
			checkUpdateReq.setLat(lat + "");
			checkUpdateReq.setLng(lng + "");
			checkUpdateReq.setDeviceType("AD_VERSION");
			checkUpdateReq.setVersionCode(Constant.currentVersion);
			CodeResult<CheckUpdateRes> reuslt = mUserModel.checkUpdate(checkUpdateReq);
			showView(reuslt);
		} catch (RetrofitError e) {
			dismissProgressDialog();
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网路不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网路不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	@UiThread
	void showView(CodeResult<CheckUpdateRes> reuslt) {
		dismissProgressDialog();
		if (reuslt != null) {
			CheckUpdateRes checkUpdateRes = reuslt.getBean();
			if (checkUpdateRes != null && checkUpdateRes.getIsUpdate() > 0) {
				checkDialog.Dialog(mContext, checkUpdateRes.getVersionName(),
						(int) (checkUpdateRes.getSize() / 1024) + "M",
						ParseUtils.convertTime(checkUpdateRes.getReleaseTime() * 1000, "yyyy年MM月dd日") + "发布",
						checkUpdateRes.getUpdateInfo().replace("<LF>", "\n"), checkUpdateRes.getDownloadUrl());
				// versionno.setText(checkUpdateRes.getVersionName());
				// versionsize.setText((int)(checkUpdateRes.getSize()/1024)+"M");
				//
				// if(checkUpdateRes.getReleaseTime()!=-1){
				// updatetime.setText(ParseUtils.convertTime(checkUpdateRes.getReleaseTime()*1000,
				// "yyyy年MM月dd日")+"发布");
				// }
				// updatelog.setText(checkUpdateRes.getUpdateInfo());
				// downloadUrl = checkUpdateRes.getDownloadUrl();
				// updatedialog.setVisibility(View.VISIBLE);
			} else {
				showToast("当前已是最新版本！");
			}
		}
	}

	// /**
	// * 下载apk
	// */
	// public void downFile(final String url){
	// pd.show();
	// new Thread(){
	// public void run(){
	// HttpClient client = new DefaultHttpClient();
	// HttpGet get = new HttpGet(url);
	// HttpResponse response;
	// try {
	// response = client.execute(get);
	// HttpEntity entity = response.getEntity();
	// long length = entity.getContentLength();
	// InputStream is = entity.getContent();
	// FileOutputStream fileOutputStream = null;
	// if(is != null){
	// File file = new
	// File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK);
	// fileOutputStream = new FileOutputStream(file);
	// byte[] b = new byte[1024];
	// int charb = -1;
	// int count = 0;
	// while((charb = is.read(b))!=-1){
	// fileOutputStream.write(b, 0, charb);
	// count += charb;
	// }
	// }
	// fileOutputStream.flush();
	// if(fileOutputStream!=null){
	// fileOutputStream.close();
	// }
	// down();
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	// }.start();
	// }

	// Handler handler = new Handler() {
	//
	// @Override
	// public void handleMessage(Message msg) {
	//
	// super.handleMessage(msg);
	// pd.cancel();
	// update();
	// }
	// };

	// /**
	// * 下载完成，通过handler将下载对话框取消
	// */
	// public void down(){
	// new Thread(){
	// public void run(){
	// Message message = handler.obtainMessage();
	// handler.sendMessage(message);
	// }
	// }.start();
	// }

	// /**
	// * 安装应用
	// */
	// public void update(){
	// Intent intent = new Intent(Intent.ACTION_VIEW);
	// intent.setDataAndType(Uri.fromFile(new
	// File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))
	// , "application/vnd.android.package-archive");
	// startActivity(intent);
	// }

	@Override
	public boolean backOperate() {
		if (updatedialog.getVisibility() == View.VISIBLE) {
			updatedialog.setVisibility(View.GONE);
		} else {
			EventBus.getDefault().post(new EventInfoSetup());
			finish();
		}
		return true;
	}

}
